package handle

import (
	"server/game/cache"
	"server/game/handle/getter"
	"server/game/model"
	"server/share/config"
	"sort"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/cosmo"
	"github.com/hwcer/updater/dataset"
	"github.com/hwcer/yyds/context"
)

func init() {
	Register(&Getter{})
}

/*
getter 数据获取
*/

type Getter struct {
}

func (this *Getter) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*Getter, *context.Context) interface{})
	return f(this, handle)
}

// Role 角色信息
func (this *Getter) Role(c *context.Context) interface{} {
	doc := cache.GetRole(c.Player.Updater)
	return doc.All()
}

// Items 基础道具
func (this *Getter) Items(c *context.Context) interface{} {
	return getter.GetItemsWithPage(c)
}

// Daily 日常数据
//
// 最多14天
func (this *Getter) Daily(c *context.Context) interface{} {
	rows := map[int32]*model.Daily{}

	now := c.Unix()
	st := now - 30*86400
	t := times.Unix(st)
	sign, _ := t.Sign(0)

	var history []*model.History
	tx := db.Model(&model.Daily{}).Where("uid = ?", c.Uid()).Where("iid >= ?", sign).Order("iid", -1).Find(&history)
	if tx.Error != nil {
		return tx.Error
	}
	for _, v := range history {
		rows[v.IID] = &model.Daily{History: *v}
	}

	//附件今日所有对象
	iid, _ := times.New(c.Now()).Sign(0)
	day := c.Player.Document(config.ITypeDaily)
	rows[iid] = day.Any().(*model.Daily)

	var arr []*model.Daily
	for _, v := range rows {
		arr = append(arr, v)
	}

	sort.Slice(arr, func(i, j int) bool {
		return arr[i].IID > arr[j].IID
	})
	return arr
}

// Task 获取任务记录
// 使用update 支持增量更新
func (this *Getter) Task(c *context.Context) interface{} {
	paging := &cosmo.Paging{}
	err := c.Bind(paging)
	if err != nil {
		return err
	}
	paging.Rows = []*model.Task{}
	paging.Init(100)
	tx := db.Omit("oid", "uid", "update").Order("update", -1).Page(paging, "uid = ?", c.Uid())
	if tx.Error != nil {
		return tx.Error
	}
	return paging
}

func (this *Getter) Record(c *context.Context) interface{} {
	var rows []*model.Record
	coll := c.Player.Collection(config.ITypeRecord)
	coll.Range(func(id string, doc *dataset.Document) bool {
		v := doc.Any().(*model.Record)
		rows = append(rows, v)
		return true
	})
	return rows
}
